import { defineStore } from 'pinia'
import { useTost } from '@/utils/comps'
import { adj } from '@/apis/ttsa'
import { equ } from '../../package-env'

export const useNetworkStore = defineStore({
  id: 'networkStore',
  state: () => ({
    list: equ === 'pc' ? [
      { label: '蓝光', value: 'extreme', id: 'def_5', key: 8 },
      { label: '超清', value: 'ultra', id: 'def_4', key: 4 },
      { label: '高清', value: 'high', id: 'def_3', key: 2 },
      { label: '标清', value: 'medium', id: 'def_2', key: 1 },
      { label: '流畅', value: 'low', id: 'def_1', key: 0.5 },
    ] : [
      // { label: '蓝光', value: 'extreme', id: 'def_5', key: 8 },
      // { label: '超清', value: 'ultra', id: 'def_4', key: 4 },
      { label: '高清', value: 'high', id: 'def_3', key: 2 },
      { label: '标清', value: 'medium', id: 'def_2', key: 1 },
      { label: '流畅', value: 'low', id: 'def_1', key: 0.5 },
    ],
    loading: false,
    bitrate: Number(localStorage.getItem('x-bitrate')) || 1,
    // 清晰度统计
    tipCount: 1,
    // 网络状态
    network: 'good',
    // 网络状态时间变量
    networkTimer: null,
  }),
  actions: {
    check() {
      if (this.tipCount > 0) {
        useTost(
          this.bitrate > 0.5 ? '检测到你当前网络不稳定，建议切换清晰度' : '检测到您当前的网络不稳定，建议切换网络环境', equ === 'pc' ? 'network-error' : 'info'
        )
        this.tipCount--
      }
      if (this.networkTimer) clearTimeout(this.networkTimer)
      this.network = 'bad'
      this.networkTimer = setTimeout(() => {
        this.network = 'good'
      }, 5000)
    },
    getIndex(v) {
      const index = this.list.findIndex((n) => n.value === v)
      return index
    },
    getValue() {
      const item = this.list.find((n) => n.key === this.bitrate)
      return item?.value
    },
    getKey(v) {
      const item = this.list.find((n) => n.value === v)
      return item?.key
    },
    adj(v, noToast?: boolean) {
      this.loading = true
      return adj(v).then(() => {
        this.loading = false
        this.bitrate = this.getKey(v)
        localStorage.setItem('x-bitrate', String(this.bitrate))
        localStorage.setItem('x-bitrate-name', v)
        !noToast && useTost('切换成功', 'pc-success', equ === 'pc')
      })
        .finally(() => {
          this.loading = false
        })
    }
  }
})
